"""
@作者：
@文件名：
@时间：
@文档说明:
"""

import snap7
from snap7.util import *

plc = snap7.client.Client()
plc.set_connection_type(3)


# 定义Plc连接
def plc_connect(ip, rack, slot):
    plc.connect(ip, rack, slot)
    if plc.get_connected():
        print("Connected")


def mReadbool(byte, bit):
    data = plc.read_area(snap7.types.Areas.MK, 0, byte, 1)
    return get_bool(data, 0, bit)


def iReadBool(byte, bit):
    """
    输入映像区的读操作
    @param byte:
    @param bit:
    @return:
    """
    data = plc.read_area(snap7.types.Areas.PE, 0, byte, 1)
    return get_bool(data, 0, bit)


def mRead(byte):
    """
    M区的读操作--------int/word/dint/dword
    @param byte:
    @return:
    """
    data = plc.read_area(snap7.types.Areas.MK, 0, byte, 4)
    print(get_int(data, 0))


def mWrite(byte, bit, value):
    """
    M区写操作，修改布尔型变量
    @param byte:
    @param bit:
    @param value:
    @return:
    """
    data = plc.read_area(snap7.types.Areas.MK, 0, byte, 1)
    set_bool(data, 0, bit, value)
    plc.write_area(snap7.types.Areas.MK, 0, byte, data)


def mWrite2(byte, value):
    """
    M区写操作，修改字节、整型、双整型变量
    @param byte:
    @param value:
    @return:
    """
    data = plc.read_area(snap7.types.Areas.MK, 0, byte, 4)
    set_dint(data, 0, value)
    # set_dint(data, 0, value)
    # set_byte(data, 0, value )
    plc.write_area(snap7.types.Areas.MK, 0, byte, data)


def read_Vblock(num, length):
    """
    @param num: 字节地址
    @param length: 字节长度
    @return:
    """
    vb_data = plc.db_read(1, num, length)
    data = get_int(vb_data[length - 1], 0)
    return data


def read_VD_real(offset):
    """
    读取速度(浮点型数据)
    @param client:
    @param offset:
    @return:
    """
    data = plc.read_area(snap7.types.Areas.DB, 1, offset, 4)
    return get_real(data, 0)


def read_VD_int(offset):
    """
    读取位置(有符号整数型数据)
    @param client:
    @param offset:
    @return:
    """
    data = plc.read_area(snap7.types.Areas.DB, 2, offset, 4)
    return get_dint(data, 0)


# V区的读操作 ------bool/int/word/dint/dword(200专用)
def write_VD(dblength, value):
    """
    @param dblength:
    @param value:
    @return:
    """
    data = plc.read_area(snap7.types.Areas.DB, 1, 0, dblength + 4)
    # set_bool(data, 0, 0, False)
    set_real(data, dblength, value)
    plc.write_area(snap7.types.Areas.DB, 1, 0, data)


if __name__ == '__main__':
    plc_connect('192.168.10.244', 0, 1)
    write_VD(230, 5.0)
    write_VD(240, 5.0)
    print(read_VD_real(350))
